/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.opgea.qms.listeners;

import com.opgea.qms.constraints.ApplicationConstraints;
import com.opgea.qms.dao.util.HibernateUtil;
import com.opgea.qms.domain.entities.Company;
import com.opgea.qms.domain.model.CurrentTokenModel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

/**
 *
 * @author Ramesh
 */
@Service
public class TokenContextLoaderListener implements ServletContextListener{

    public static Map<Long, CurrentTokenModel> currentTokenMap =
                new HashMap<Long, CurrentTokenModel>();
    
    private Session session = HibernateUtil.getSessionFactory().openSession();
    
    public List<Company> findAllCompanies(){
        List<Company> companies = session.createQuery("from Company").list();
        return companies;
    }
    
    public Integer getMaxTokenNumber(Long companyId, String dateString){
        /*
        Date today = Calendar.getInstance(Locale.US).getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(today);
         * 
         */
        Query query = session.createQuery("SELECT max(t.tokenNo) FROM Token t "
                + " WHERE t.company.id = "+companyId+" AND "
                + " t.tokenDate = '"+dateString+"' ");
        System.out.println("TokenContextLoaderListener: "+query.getQueryString());
        return (Integer) query.uniqueResult();
    }
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Date today = Calendar.getInstance(Locale.US).getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(today);
        
        ServletContext servletContext = sce.getServletContext();
        
        servletContext.setAttribute(ApplicationConstraints.CURRENT_TOKEN_MAP.name(), currentTokenMap);
        System.out.println("Token Context Loader Initialized...");
        
        List<Company> companies = this.findAllCompanies();
        if(companies != null){
            for(Company company : companies){
                CurrentTokenModel model = new CurrentTokenModel();
                model.setCompanyId(company.getId());
                model.setCurrentTokenNumber(this.getMaxTokenNumber(company.getId(), dateString));
                model.setToday(Calendar.getInstance().getTime());
                currentTokenMap.put(company.getId(), model);
            }
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        servletContext.removeAttribute(ApplicationConstraints.CURRENT_TOKEN_MAP.name());
        System.out.println("Token Context Loader Destroyed...");
    }
    
}
